#include "publicFunction.h"
#include <time.h>

namespace PUBLIC
{
 
};

string PUBLIC::ws2s(const wstring& ws)
{
	string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";

	setlocale(LC_ALL, "chs"); 

	const wchar_t* _Source = ws.c_str();
	size_t _Dsize = 2 * ws.size() + 1;
	char *_Dest = new char[_Dsize];
	memset(_Dest,0,_Dsize);
	wcstombs(_Dest,_Source,_Dsize);
	string result = _Dest;
	delete []_Dest;

	setlocale(LC_ALL, curLocale.c_str());

	return result;
}

wstring PUBLIC::s2ws(const string& s)
{
	setlocale(LC_ALL, "chs"); 

	const char* _Source = s.c_str();
	size_t _Dsize = s.size() + 1;
	wchar_t *_Dest = new wchar_t[_Dsize];
	wmemset(_Dest, 0, _Dsize);
	mbstowcs(_Dest,_Source,_Dsize);
	wstring result = _Dest;
	delete []_Dest;

	setlocale(LC_ALL, "C");

	return result;
}


wstring PUBLIC::NumberToWstring(long long Num)   
{
	wchar_t buffer[40]={0};
	swprintf(buffer,L"%I64d",Num);
	wstring strBuf=buffer;

	return strBuf;
}

bool PUBLIC::is_leap(int year)
{   
	if(year%4==0)
	{   
		if(year%100!=0||year%400==0)
			return true;        
	}
	return false;
}

bool PUBLIC::IsDTStrValid(const char *pDTStr)
{
	if(pDTStr==NULL)
		return false;

	int num=0;
	int year=0;
	int month=0;
	int day=0;
	int hour=0;
	int minute=0;
	int second=0;

	num=sscanf(pDTStr, "%04d-%02d-%02d %02d:%02d:%02d", &year, &month, &day, &hour, &minute, &second);
	if(num==6 && year>1900 && year<2100 && month<13 && month>0 && hour>=0 && hour<=24 && minute>=0 && minute<60 && second>=0 && second<60)
	{
		static int daysofmonth[]={31,28,31,30,31,30,31,31,30,31,30,31}; 
		if(is_leap(year))
			daysofmonth[1]=29;
		else
			daysofmonth[1]=28;
		if(day>0 && day<=daysofmonth[month-1])
			return true;
		else
			return false;
	}

	return false;
}

string PUBLIC::get_datetime_string(const EASY_DATA_TIME * pDT)
{
	if(pDT==NULL)
		return "";

	if(pDT->iYear==0 && pDT->iMon==0 && pDT->iDay==0 && pDT->iHour==0 && pDT->iMin==0 && pDT->iSec==0)
		return "";

	char szTmp[32];
	memset(szTmp, 0, sizeof(szTmp));

	_snprintf(szTmp, sizeof(szTmp)-1, "%04d-%02d-%02d %02d:%02d:%02d",
		pDT->iYear,
		pDT->iMon,
		pDT->iDay,
		pDT->iHour, 
		pDT->iMin, 
		pDT->iSec
		);

	return szTmp;
}

PUBLIC::EASY_DATA_TIME PUBLIC::Now(long long lldiffsec)
{
	EASY_DATA_TIME dt;

	long long now = time(NULL);
	now+=lldiffsec;
	struct tm *tim = localtime(&now);
	dt.iDay = tim->tm_mday;
	dt.iMon = tim->tm_mon + 1;
	dt.iYear = tim->tm_year+1900;
	dt.iHour=tim->tm_hour;
	dt.iMin=tim->tm_min;
	dt.iSec=tim->tm_sec;

	return dt;
}